//
//  ZDBMainTabBar.swift
//  XinLangMicroblog
//
//  Created by MackBook on 16/9/22.
//  Copyright © 2016年 zx540006260. All rights reserved.
//

import UIKit

class ZDBMainTabBar: UITabBar {
 
    //声明一个闭包:用来想控制器传递中间按钮的点击事件,这个类型+()?
    
    var composeClosure : (() -> ())?
    
    override init(frame: CGRect) {
        
        super.init(frame: frame)
        
        addSubview(composeButton)
        
        composeButton.addTarget(self, action: #selector(clickComposeButton), for: .touchUpInside)
        
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
  @objc private  func clickComposeButton (){
        
    //执行闭包,这里要是!强制解包:没有实现会导致崩溃
    
    composeClosure? ()
    
    }
    
    override func layoutSubviews() {
        
        //必须添加 super
        
        super.layoutSubviews()
        
        let buttonW = self.bounds.width / 5
        
        let buttonH = self.bounds.height
        
        var index = 0
        
        for subView in subviews {
            
            if subView.isKind(of: NSClassFromString("UITabBarButton")!){
                
                subView.frame = CGRect(x: CGFloat(index) * buttonW, y: 0, width: buttonW, height: buttonH)
                
                index += (index == 1) ? 2 : 1
                
            }
            
        }
        
        //MARK:撰写中间按钮的位置
        
        //大小
        
        composeButton.bounds.size = CGSize(width: buttonW, height: buttonH)
        
        //位置
        
        composeButton.center = CGPoint(x: self.center.x, y: self.bounds.height * 0.5)
        
    }
    //MARK:懒加载撰写按钮
    
  private  lazy var composeButton : UIButton = {
        
        let button = UIButton()
        
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add"), for: .normal)
        button.setImage(#imageLiteral(resourceName: "tabbar_compose_icon_add_highlighted"), for: .highlighted)
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button"), for: .normal)
        button.setBackgroundImage(#imageLiteral(resourceName: "tabbar_compose_button_highlighted"), for: .highlighted)
        
        return button
    }()
}
